<?php

class Light_Request
{
    /**
     * @var array
     */
    protected $_params = array();

    /**
     * @param array $params
     */
    public function __construct(array $params = array())
    {
        $this->_params = $params;
    }

	/**
     * Get server variable
     *
     * @param string $key
     * @return string
     */
    public function getServer($key = null)
    {
        if ($key === null) {
            return $_SERVER;
        }

        return isset($_SERVER[$key]) ? $_SERVER[$key] : null;
    }

    /**
     * Get header
     *
     * @param string $header
     * @return string
     */
    public function getHeader($header)
    {
        if (empty($header)) {
            throw new Light_Exception('Header name is required', 500);
        }

        $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));

        if (isset($_SERVER[$temp]) && !empty($_SERVER[$temp])) {
            return $_SERVER[$temp];
        }

        return false;
    }

    /**
     * Get param
     *
     * @param string $key
     * @param string $default
     * @return string|null
     */
    public function getParam($key, $default = null)
    {
        if (isset($this->_params[$key])) {
            return $this->_params[$key];
        }

        return $default;
    }

    /**
     * Set param
     *
     * @param string $key
     * @param string $value
     * @return Light_Request
     */
    public function setParam($key = null, $value = null)
    {
        $this->_params[$key] = $value;

        return $this;
    }

    /**
     * Set params
     *
     * @param array $params
     * @return Light_Request
     */
    public function setParams(array $params)
    {
        foreach ($params as $key => $value) {
            $this->setParam($key, $value);
        }

        return $this;
    }

	/**
	 * Check for post
	 *
	 * @return boolean
	 */
	public function getPost($key = null, $default = null)
	{
		if ($key === null) {
			return $_POST;
		}

		return isset($_POST[$key]) ? $_POST[$key] : $default;
	}

	/**
	 * Check for post
	 *
	 * @return boolean
	 */
	public function isPost()
	{
		return ($_SERVER['REQUEST_METHOD'] == 'POST');
	}

	/**
	 * Check for AJAX
	 *
	 * @return boolean
	 */
	public function isAjax()
	{
	    return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest');
	}

	/**
	 * Get params
	 *
	 * @return array
	 */
	public function getParams()
	{
	    return $this->_params;
	}
}